// 游戏交互逻辑文件
// antiShake(jianPan, 50)
$(document).keydown(antiShake(jianPan, 50))
function jianPan(event) {
  switch (event.keyCode) {
    // 左
    case 37:
      if (move('left')) {
        console.log(1)
        getScore()
        generatOneNumber()
        isGameOver()
      }
      break
    // 上
    case 38:
      if (move('top')) {
        getScore()
        generatOneNumber()
        isGameOver()
      }
      break
    // 右
    case 39:
      if (move('right')) {
        getScore()
        generatOneNumber()
        isGameOver()
      }
      break
    // 下
    case 40:
      if (move('bottom')) {
        getScore()
        generatOneNumber()
        isGameOver()
      }
      break
  }
}

// 移动
function move(direction) {
  // 左移动
  if (direction === 'left') {
    // 格子无法移动
    if (!canMove(board, direction)) return false
    isaddedArray()
    // 移动
    for (let i = 0; i < 4; i++) {
      // 第一列无法向左移动，直接排除
      for (let j = 1; j < 4; j++) {
        if (board[i][j] !== 0) {
          // 判断
          for (let k = 0; k < j; k++) {
            // 1.当前值不为0的数值格左边的数值格必须为0并且中间的数值和也为0
            if (board[i][k] === 0 && thereAnyObstacles(i, k, j, board, direction)) {
              // 移动
              showMoveAnimation(i, j, i, k)
              board[i][k] = board[i][j]
              board[i][j] = 0
              continue
            }
            // 2.当前值不为0的数值格与左边的数值格相等并且中间的数值格必须也为0
            else if (board[i][k] === board[i][j] && thereAnyObstacles(i, k, j, board, direction)) {
              // 移动
              showMoveAnimation(i, j, i, k)
              if (added[i][k] !== 0) {
                board[i][k + 1] = board[i][j]
                board[i][j] = 0
              } else {
                board[i][k] += board[i][j]
                board[i][j] = 0
                added[i][k] = 1
                score += board[i][k]
              }
              continue
            }
          }
        }
      }
    }
    setTimeout('updateBoardView()', 200)
    return true
  }
  // 右移动
  if (direction === 'right') {
    // 格子无法移动
    if (!canMove(board, direction)) return false
    isaddedArray()
    // 移动
    for (let i = 0; i < 4; i++) {
      for (let j = 2; j >= 0; j--) {
        if (board[i][j] !== 0) {
          // 判断
          for (let k = 3; k > j; k--) {
            if (board[i][k] === 0 && thereAnyObstacles(i, j, k, board, direction)) {
              // 移动
              showMoveAnimation(i, j, i, k)
              board[i][k] = board[i][j]
              board[i][j] = 0
              continue
            } else if (
              board[i][k] === board[i][j] &&
              thereAnyObstacles(i, j, k, board, direction)
            ) {
              // 移动
              showMoveAnimation(i, j, i, k)
              if (added[i][k] !== 0) {
                board[i][k - 1] = board[i][j]
                board[i][j] = 0
              } else {
                board[i][k] += board[i][j]
                board[i][j] = 0
                added[i][k] = 1
                score += board[i][k]
              }
              continue
            }
          }
        }
      }
    }
    setTimeout('updateBoardView()', 200)
    return true
  }
  // 上移动
  if (direction === 'top') {
    // 格子无法移动
    if (!canMove(board, direction)) return false
    isaddedArray()
    // 移动
    for (let i = 0; i < 4; i++) {
      for (let j = 1; j < 4; j++) {
        if (board[j][i] !== 0) {
          // 判断
          for (let k = 0; k < j; k++) {
            if (board[k][i] === 0 && thereAnyObstacles(i, k, j, board, direction)) {
              // 移动
              showMoveAnimation(j, i, k, i)
              board[k][i] = board[j][i]
              board[j][i] = 0
              continue
            } else if (
              board[k][i] === board[j][i] &&
              thereAnyObstacles(i, k, j, board, direction)
            ) {
              // 移动
              showMoveAnimation(j, i, k, i)
              if (added[k][i] !== 0) {
                board[k + 1][i] = board[j][i]
                board[j][i] = 0
              } else {
                board[k][i] += board[j][i]
                board[j][i] = 0
                added[k][i] = 1
                score += board[k][i]
              }
              continue
            }
          }
        }
      }
    }
    setTimeout('updateBoardView()', 200)
    return true
  }
  // 下移动
  if (direction === 'bottom') {
    // 格子无法移动
    if (!canMove(board, direction)) return false
    isaddedArray()
    // 移动
    for (let i = 0; i < 4; i++) {
      for (let j = 2; j >= 0; j--) {
        if (board[j][i] !== 0) {
          // 判断
          for (let k = 3; k > j; k--) {
            if (board[k][i] === 0 && thereAnyObstacles(i, j, k, board, direction)) {
              // 移动
              showMoveAnimation(j, i, k, i)
              board[k][i] = board[j][i]
              board[j][i] = 0
              continue
            } else if (
              board[k][i] === board[j][i] &&
              thereAnyObstacles(i, j, k, board, direction)
            ) {
              // 移动
              showMoveAnimation(j, i, k, i)
              if (added[k][i] !== 0) {
                board[k - 1][i] = board[j][i]
                board[j][i] = 0
              } else {
                board[k][i] += board[j][i]
                board[j][i] = 0
                added[k][i] = 1
                score += board[k][i]
              }
              continue
            }
          }
        }
      }
    }
    setTimeout('updateBoardView()', 200)
    return true
  }
}

// 移动端
// 当我点击屏幕时
$('.grid-container').on('touchstart', function (e) {
  e.preventDefault()
  startX = e.originalEvent.changedTouches[0].pageX
  startY = e.originalEvent.changedTouches[0].pageY
})
// 滑动屏幕触发事件
$('.grid-container').on('touchmove', antiShake(send, 50))
// 滑动事件
function send(e) {
  // e.preventDefault()
  moveEndX = e.originalEvent.changedTouches[0].pageX
  moveEndY = e.originalEvent.changedTouches[0].pageY
  X = moveEndX - startX
  Y = moveEndY - startY

  if (Math.abs(X) > Math.abs(Y) && X > 0) {
    // alert('left => right')
    if (move('right')) {
      getScore()
      generatOneNumber()
      isGameOver()
    }
  } else if (Math.abs(X) > Math.abs(Y) && X < 0) {
    // alert('right => left')
    if (move('left')) {
      getScore()
      generatOneNumber()
      isGameOver()
    }
  } else if (Math.abs(Y) > Math.abs(X) && Y > 0) {
    // alert('top => bottom')
    if (move('bottom')) {
      getScore()
      generatOneNumber()
      isGameOver()
    }
  } else if (Math.abs(Y) > Math.abs(X) && Y < 0) {
    // alert('bottom => top')
    if (move('top')) {
      getScore()
      generatOneNumber()
      isGameOver()
    }
  } else {
    alert('just touch')
  }
}
// 防抖函数
function antiShake(fn, delay) {
  var timerID = null
  return function () {
    var self = this
    var args = arguments
    timerID && clearTimeout(timerID)
    timerID = setTimeout(function () {
      fn.apply(self, args)
    }, delay || 500)
  }
}

// 游戏结束
function isGameOver() {
  if (nospace(board) && nomove(board)) {
    setTimeout(GameOver(), 1000)
  }
}
function GameOver() {
  $('.grid-container').append(`
  <div id="gameover" class="gameover">
    <p>本次得分</p>
    <span>${score}</span>
    <a href="javascript:restartgame();">再来一把</a>
  </div>
  `)
  // 移动端点击
  $('.gameover a').on('touchstart', function () {
    restartgame()
  })
}
function restartgame() {
  $('#gameover').remove()
  newgame()
}
